package com.campsys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campsys.domain.TManagerStudent;
import com.campsys.domain.TManagerTeacher;
import com.campsys.domain.TSysUser;
import com.campsys.domain.param.StudentAddExcel;
import com.campsys.domain.param.StudentAddParam;
import com.campsys.domain.param.UserAddParam;
import com.campsys.mapper.StudentMapper;
import com.campsys.mapper.UserMapper;
import com.campsys.mapping.StudentMapping;
import com.campsys.mapping.TeacherMapping;
import com.campsys.mapping.UserMapping;
import com.campsys.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, TManagerStudent> implements IStudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean addStudent(StudentAddParam studentAddParam) {

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123456");

        UserAddParam userAddParam = StudentMapping.INSTANCE.toUser(studentAddParam);
        userAddParam.setLoginName(studentAddParam.getStuName());
        TSysUser tSysUser = UserMapping.INSTANCE.to(userAddParam);
        tSysUser.setPassword(encode);
        tSysUser.setStatus("1");
        int rs1 = userMapper.insert(tSysUser);

        TManagerStudent tManagerStudent = StudentMapping.INSTANCE.to(studentAddParam);
        tManagerStudent.setLoginId(tSysUser.getId());
        int rs2 = studentMapper.insert(tManagerStudent);

        boolean rs3 = userMapper.addRoleIdByUserId(tSysUser.getId(),4l);

        return rs1 == 1 && rs2 == 1 && rs3 ? true : false;

    }

    @Transactional
    @Override
    public boolean deleteStudent(Long id) {
        TManagerStudent tManagerStudent = studentMapper.selectById(id);
        tManagerStudent.setDeleteStatus("1");

        TSysUser user = new TSysUser();
        user.setId(tManagerStudent.getLoginId());
        user.setStatus("2");

        int rs1 = userMapper.updateById(user);

        int rs2 = studentMapper.updateById(tManagerStudent);
        return rs1 == 1 && rs2 == 1 ? true : false;
    }

    @Transactional
    @Override
    public boolean addStudentBatch(List<StudentAddExcel> list) {
        boolean rs = false;

        List<StudentAddParam> list1 = StudentMapping.INSTANCE.to(list);

        for (StudentAddParam studentAddParam : list1){
            rs = addStudent(studentAddParam);
        }

        return rs;
    }
}
